<template>
  <div id="userRegisterPage">
    <van-nav-bar left-text="返回" left-arrow @click-left="router.back()" />
    <h2 style="text-align: center; margin-bottom: 16px">用户注册</h2>
    <van-form @submit="handleSubmit">
      <van-field
        v-model="form.userAccount"
        name="userAccount"
        label="账号"
        placeholder="请输入账号"
        :rules="[{ required: true, message: '必须输入账号！' }, { validator: (value) => value.length >= 4, message: '账号长度不能小于4位！' }]"
      />
      <van-field
        v-model="form.userPassword"
        type="password"
        name="userPassword"
        label="密码"
        placeholder="请输入密码"
        :rules="[{ required: true, message: '必须输入密码！' }]"
      />
      <van-field
        v-model="form.checkPassword"
        type="password"
        name="checkPassword"
        label="确认密码"
        placeholder="请再次输入密码"
        :rules="[{ required: true, message: '必须输入确认密码！' }]"
      />
      <div style="margin: 16px;">
        <van-button round block type="primary" native-type="submit" style="max-width: 300px; margin: 0 auto;"> 注册 </van-button>
      </div>
      <div style="display: flex; width: 100%; align-items: center; justify-content: space-around;">
        <p>已有账号？<router-link to="/auth/login">前往登录</router-link></p>
      </div>
    </van-form>
  </div>
</template>

<script setup lang="ts">
import { reactive } from "vue";
import API from "@/api";
import { showSuccessToast, showFailToast, showLoadingToast, closeToast } from 'vant';
import { useRouter } from "vue-router";

const router = useRouter();

const form = reactive({
  userAccount: "",
  userPassword: "",
  checkPassword: "",
} as API.UserRegisterRequest);

/**
 * 提交
 */
const handleSubmit = async () => {
  const { userPassword, checkPassword } = form;
  if (userPassword !== checkPassword) {
    showFailToast("两次输入的密码不一致！");
    return;
  }
  showLoadingToast({
    message: '注册中...',
    forbidClick: true,
  });
  const res = await API.userController.userRegister(form);
  closeToast();
  if (res.data.code === 200) {
    showSuccessToast("注册成功");
    router.push({
      path: "/auth/login",
      replace: true,
    });
  } else {
    showFailToast("注册失败，" + res.data.message);
  }
};
</script>
